package gui;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.Date;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JOptionPane;
import model.Artist;
import model.MusicGroup;
import org.eclipse.persistence.internal.jpa.rs.metadata.model.Query;



public class ListArtistForm extends javax.swing.JFrame {

    //Πεδία
    private EntityManager em;
    private MainForm parent;
    private Artist selectedArtist;
    
    public ListArtistForm(EntityManager em, MainForm parent) {
        this.em=em;
        this.parent=parent;
        initComponents();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        artistQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT a FROM Artist a");
        artistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(artistQuery.getResultList());
        titleLabel = new javax.swing.JLabel();
        artistScrollPane = new javax.swing.JScrollPane();
        artistTable = new javax.swing.JTable();
        newButton = new javax.swing.JButton();
        editButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();

        jLabel1.setText("jLabel1");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Αρχείο καλλιτεχνών");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        titleLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        titleLabel.setText("Διαχείριση καλλιτεχνών");

        artistTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, artistList, artistTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${firstName}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${lastName}"));
        columnBinding.setColumnName("Επώνυμο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artisticName}"));
        columnBinding.setColumnName("Καλλιτεχνικό όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${sex}"));
        columnBinding.setColumnName("Φύλο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${birthday}"));
        columnBinding.setColumnName("Ημερ. γέννησης");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${birthplace}"));
        columnBinding.setColumnName("Τόπος γέννησης");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${musicGenre}"));
        columnBinding.setColumnName("Μουσικό είδος");
        columnBinding.setColumnClass(model.MusicGenre.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        artistScrollPane.setViewportView(artistTable);

        newButton.setText("Εισαγωγή");
        newButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newButtonActionPerformed(evt);
            }
        });

        editButton.setText("Μεταβολή");
        editButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editButtonActionPerformed(evt);
            }
        });

        deleteButton.setText("Διαγραφή");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        exitButton.setText("Έξοδος");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(151, 151, 151)
                .addComponent(titleLabel)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(artistScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(newButton)
                .addGap(29, 29, 29)
                .addComponent(editButton)
                .addGap(43, 43, 43)
                .addComponent(deleteButton)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(exitButton))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(titleLabel)
                .addGap(18, 18, 18)
                .addComponent(artistScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newButton)
                    .addComponent(editButton)
                    .addComponent(deleteButton))
                .addGap(19, 19, 19)
                .addComponent(exitButton)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        
        //Ενεργοποίηση γονικού παραθύρου
        parent.setEnabled(true);
        //Το τρέχον παράθυρο κλείνει
        dispose();
        
    }//GEN-LAST:event_formWindowClosing

    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        
        //Δημιουργία νέου καλλιτέχνη
        selectedArtist=new Artist(null);
        selectedArtist.setFirstName("DIMITRIS");
        selectedArtist.setLastName("IOANNOU");
        selectedArtist.setArtisticName("DIMITRIS");
        selectedArtist.setSex("M");
        selectedArtist.setBirthday(new Date());
        selectedArtist.setBirthplace("ATHENS");
        Query selectGenres=em.createQuery("Select m FROM Music Genre m");
        List<MusicGenre> genres=selectGenres.getResultList();
        selectedArtist.setMusicGenre(genres.get(0));
        
        //Τον γράφω στη ΒΔ
        if(!em.getTransaction().isActive())
            em.getTransaction().begin();
        em.persist(selectedArtist);
        em.flush();
        
        //Δημιουργία φόρμας EditArtistForm
        EditArtistForm editArtistForm=new EditArtistForm(em,selectedArtist);
        editArtistForm.setVisible(true);
        setEnabled(false);
        
        //Add
        // Διαχείριση παραθύρων
        editArtistForm.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                if (((MyWindowEvent)arg0).exitAndSave) {
                    // Περίπτωση επιβεβαίωσης
                    //Πρόσθεσε τον καλλιτέχνη στη λίστα καλλιτεχνών
                    artistList.add(selectedArtist);
                    //Επέλεξε τον στον πίνακα
                    int row=artistList.size()-1;
                    artistTable.setRowSelectionInterval(row,row);
                    artistTable.scrollRectToVisible(artistTable.getCellRect(row,0,true));
                    
                } else {
                    // Περίπτωση ακύρωσης
                    em.remove(selectedArtist);
                    
                }
                // Ενεργοποίησε και πάλι την τρέχουσα φόρμα
                setEnabled(true);
                // Τερμάτισε την δοσοληψία με την Βάση Δεδομένων
                em.getTransaction().commit();
            }
            public void windowActivated(WindowEvent arg0) { }
            public void windowClosing(WindowEvent arg0) { }
            public void windowDeactivated(WindowEvent arg0) { }
            public void windowDeiconified(WindowEvent arg0) { }
            public void windowIconified(WindowEvent arg0) { }
            public void windowOpened(WindowEvent arg0) { }
        });
    }//GEN-LAST:event_newButtonActionPerformed

    private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
        
        //Έλεγχος αν έχει επιλεγεί καλλιτέχνης
        int row=artistTable.getSelectedRow();
        
        if (row==-1){
            JOptionPane.showMessageDialog(this, "Δεν έχει επιλεγεί καλλιτέχνης",
                                            "Σφάλμα", JOptionPane.WARNING_MESSAGE);
        return;
        } 
        
        //Ανάκτηση καλλιτέχνη
        selectedArtist=artistList.get(row);
        
        //Εκκίνηση δοσοληψίας
        if(!em.getTransaction().isActive())
            em.getTransaction().begin();
        
        //Δημιουργία φόρμας EditArtistForm
        EditArtistForm editArtistForm=new EditArtistForm(em,selectedArtist);
        editArtistForm.setVisible(true);
        setEnabled(false);
        
        //Edit
// Διαχείριση παραθύρων
        editArtistForm.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                if (((MyWindowEvent)arg0).exitAndSave) {
                    // Περίπτωση επιβεβαίωσης
                    artistTable.setRowSelectionInterval(row,row);
                    artistTable.scrollRectToVisible(artistTable.getCellRect(row,0,true));
                } else {
                    // Περίπτωση ακύρωσης
                    // Μετέφερε το αντικείμενο στην προηγούμενη κατάστασή του
                    em.refresh(selectedArtist);
                    // Ανανέωσε τις πληροφορίες στον πίνακα
                    List<Artist> artistData = artistQuery.getResultList();
                    artistList.clear();
                    artistList.addAll(artistData);
                }
                // Ενεργοποίησε και πάλι την τρέχουσα φόρμα
                setEnabled(true);
                // Τερμάτισε την δοσοληψία με την Βάση Δεδομένων
                em.getTransaction().commit();
            }
            public void windowActivated(WindowEvent arg0) { }
            public void windowClosing(WindowEvent arg0) { }
            public void windowDeactivated(WindowEvent arg0) { }
            public void windowDeiconified(WindowEvent arg0) { }
            public void windowIconified(WindowEvent arg0) { }
            public void windowOpened(WindowEvent arg0) { }
        });
        
    }//GEN-LAST:event_editButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        
        //Έλεγχος αν έχει επιλεγεί καλλιτέχνης
        int row=artistTable.getSelectedRow();
        
        if (row==-1){
            JOptionPane.showMessageDialog(this, "Δεν έχει επιλεγεί καλλιτέχνης",
                                            "Σφάλμα", JOptionPane.WARNING_MESSAGE);
        return;
        } 
        
        //Επιβεβαίωση διαγραφής
        int choice=JOptionPane.showConfirmDialog(this,"Διαγραφή καλλιτέχνη",
                    "Επιβεβαίωση διαγραφής καλλιτέχνη", JOptionPane.YES_NO_OPTION);
        
        if(choice!=0)
            return;
        
        //Ανάκτηση του προς διαγραφή καλλιτέχνη
        Artist artistToRemove=artistList.get(row);
        
        //Δημιουργία νεάς δοσοληψίας
        if(!em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        
        //Διαγραφή του καλλιτέχνη από τα συγκροτήματα που ανήκει
        for (MusicGroup mg:artistToRemove.getMusicGroupList()){
            mg.getArtistList().remove(artistToRemove);
        }
        
        //Σβήνω τον καλλιτέχνη απο τη ΒΔ
        em.remove(artistToRemove);
        
        //Σβήνω τον καλλιτέχνη από το List
        em.remove(artistToRemove);
        
        //Τερματισμός δοσοληψίας
        em.getTransaction().commit();
        
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        
        //Ενεργοποίηση γονικού παραθύρου
        parent.setEnabled(true);
        //Το τρέχον παράθυρο κλείνει
        dispose();
    }//GEN-LAST:event_exitButtonActionPerformed

    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<model.Artist> artistList;
    private javax.persistence.Query artistQuery;
    private javax.swing.JScrollPane artistScrollPane;
    private javax.swing.JTable artistTable;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton editButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton newButton;
    private javax.swing.JLabel titleLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
